import { defineStore } from 'pinia'
import { messagesApi } from '../utils/apiService'
import { useUserStore } from './user'

export const useNotificationStore = defineStore('notification', {
    state: () => ({
        notifications: [
            {
                id: 1,
                title: '物品即将过期',
                content: '牛奶将在3天后过期，请及时使用。',
                type: 'expiry',
                time: '2023-10-15 10:30',
                read: false
            },
            {
                id: 2,
                title: '库存不足提醒',
                content: '卫生纸库存不足，当前剩余2个。',
                type: 'inventory',
                time: '2023-10-14 16:45',
                read: false
            },
            {
                id: 3,
                title: '系统更新通知',
                content: '系统已更新到最新版本 v1.2.0，新增了多项功能。',
                type: 'system',
                time: '2023-10-10 09:15',
                read: true
            },
            {
                id: 4,
                title: '新用户加入',
                content: '用户 张三 已被添加到您的家庭组。',
                type: 'system',
                time: '2023-10-05 14:20',
                read: true
            }
        ],
        settings: {
            types: ['system', 'inventory', 'expiry', 'updates'],
            methods: ['app', 'email']
        },
        loading: false,
        page: 1,
        pageSize: 10,
        total: 0,
        hasMore: true
    }),

    getters: {
        allNotifications: (state) => {
            return [...state.notifications].sort((a, b) => new Date(b.time) - new Date(a.time))
        },
        unreadNotifications: (state) => {
            return state.notifications.filter(notification => !notification.read)
                .sort((a, b) => new Date(b.time) - new Date(a.time))
        },
        unreadCount: (state) => {
            return state.notifications.filter(notification => !notification.read).length
        }
    },

    actions: {
        // 从后端获取通知列表
        async fetchNotifications(userId = null, isRead = null, page = 1) {
            this.loading = true;

            try {
                // 获取位置ID
                const locationId = this.getFirstLocationId();

                // 如果没有位置ID，则无法加载通知
                if (!locationId) {
                    console.warn('无法获取位置ID，无法加载通知');
                    return false;
                }

                console.log(`准备使用位置ID ${locationId} 获取消息数据...`);

                // 构建请求参数
                const params = {
                    locationId: locationId,
                    getAllData: true // 获取所有数据，不分页
                };

                console.log('发送消息请求参数:', params);

                const response = await messagesApi.getMessages(params);

                console.log('获取消息响应:', response);

                if (response && response.code === 200 && response.data) {
                    this.processNotificationsResponse(response, isRead);
                    return true;
                } else {
                    console.warn('获取通知列表失败:', response);
                    return false;
                }
            } catch (error) {
                console.error('获取通知数据出错:', error);
                return false;
            } finally {
                this.loading = false;
            }
        },

        // 处理通知响应数据
        processNotificationsResponse(response, isRead = null) {
            // 转换后端数据格式为前端格式，仅过滤出通知类型的消息
            const allMessages = response.data.list || [];
            const notificationList = allMessages.filter(item =>
                item.messageType === 'notification' && // 使用驼峰 messageType
                ['system', 'inventory', 'expiry', 'updates', 'login', 'permission'].includes(item.subType) // 使用驼峰 subType
            );

            // 如果有isRead参数，进一步过滤
            const filteredNotifications = isRead !== null
                ? notificationList.filter(item => item.isRead === (isRead ? 1 : 0)) // 使用驼峰 isRead
                : notificationList;

            const mappedNotifications = filteredNotifications.map(item => ({
                id: item.id,
                title: item.title,
                content: item.content,
                type: item.subType,
                time: item.createTime,
                read: item.isRead === 1,
                priority: item.priority,
                locationId: item.locationId,
                itemId: item.itemId
            }));

            // 替换现有通知
            this.notifications = mappedNotifications;
            this.total = response.data.total || mappedNotifications.length;
            this.hasMore = false; // 已获取所有数据，无需分页
            this.page = 1;

            console.log(`成功获取到 ${mappedNotifications.length} 条通知`);
        },

        // 加载更多通知
        async loadMoreNotifications() {
            if (this.loading || !this.hasMore) return false;

            const nextPage = this.page + 1;
            return await this.fetchNotifications(null, null, nextPage);
        },

        // 标记单个通知为已读
        async markAsRead(id) {
            try {
                const response = await messagesApi.markAsRead(id);

                if (response && response.code === 200) {
                    // 更新本地状态
                    const notification = this.notifications.find(n => n.id === id);
                    if (notification) {
                        notification.read = true;
                    }
                    return true;
                } else {
                    console.warn('标记通知已读失败:', response);
                    return false;
                }
            } catch (error) {
                console.error('标记通知已读出错:', error);
                return false;
            }
        },

        // 标记所有通知为已读
        async markAllAsRead() {
            try {
                // 获取第一个位置ID作为参数
                const locationId = this.getFirstLocationId();

                if (!locationId) {
                    console.warn('无法获取位置ID，无法标记通知为已读');
                    return false;
                }

                const response = await messagesApi.markAllAsRead(null, locationId);

                if (response && response.code === 200) {
                    // 更新本地状态
                    this.notifications.forEach(notification => {
                        notification.read = true;
                    });
                    return true;
                } else {
                    console.warn('标记所有通知已读失败:', response);
                    return false;
                }
            } catch (error) {
                console.error('标记所有通知已读出错:', error);
                return false;
            }
        },

        // 获取位置ID，优先使用当前选择的位置ID
        getFirstLocationId() {
            try {
                // 1. 首先尝试从localStorage获取当前选择的位置ID
                const currentLocationId = localStorage.getItem('currentLocationId');
                if (currentLocationId) {
                    console.log('从localStorage获取到当前位置ID:', currentLocationId);
                    return currentLocationId;
                }

                // 2. 如果没有localStorage中的ID，再使用权限store中的第一个位置
                const { usePermissionStore } = require('./permission');
                const permissionStore = usePermissionStore();
                const userLocations = permissionStore.userLocationPermissions;

                if (!userLocations || Object.keys(userLocations).length === 0) {
                    console.warn('用户没有位置权限');
                    return null;
                }

                const firstLocationId = Object.keys(userLocations)[0];
                console.log('使用权限列表中的第一个位置ID:', firstLocationId);
                return firstLocationId;
            } catch (error) {
                console.error('获取位置ID出错:', error);
                return null;
            }
        },

        // 添加新通知
        async addNotification(notification) {
            const userStore = useUserStore();
            const userId = userStore.getUser?.id;

            if (!userId) {
                console.warn('无法获取用户ID，无法添加通知');
                return false;
            }

            try {
                // 准备通知数据，适配后端格式
                const messageData = {
                    messageType: 'notification',
                    title: notification.title,
                    content: notification.content,
                    subType: notification.type,
                    userId: userId,
                    locationId: notification.locationId,
                    itemId: notification.itemId,
                    priority: notification.priority || 0,
                    isRead: 0
                };

                const response = await messagesApi.createMessage(messageData);

                if (response && response.code === 200 && response.data) {
                    // 不再将新通知添加到本地状态
                    // 每次获取最新通知时会从服务器刷新
                    return true;
                } else {
                    console.warn('创建通知失败:', response);
                    return false;
                }
            } catch (error) {
                console.error('创建通知出错:', error);
                return false;
            }
        },

        // 删除通知
        async deleteNotification(id) {
            try {
                // 调用后端API删除通知
                const response = await messagesApi.deleteMessage(id);

                if (response && response.code === 200) {
                    return true;
                } else {
                    console.warn('删除通知失败:', response);
                    return false;
                }
            } catch (error) {
                console.error('删除通知出错:', error);
                return false;
            }
        },

        // 更新通知设置
        async updateSettings(settings) {
            const userStore = useUserStore();
            const userId = userStore.getUser?.id;

            if (!userId) {
                console.warn('无法获取用户ID，无法更新通知设置');
                return false;
            }

            try {
                const response = await messagesApi.updateUserSettings(userId, {
                    notification_settings: settings
                });

                if (response && response.code === 200) {
                    this.settings = { ...settings };
                    return true;
                } else {
                    console.warn('更新通知设置失败:', response);
                    return false;
                }
            } catch (error) {
                console.error('更新通知设置出错:', error);
                return false;
            }
        },

        // 获取用户通知设置
        async fetchSettings() {
            const userStore = useUserStore();
            const userId = userStore.getUser?.id;

            if (!userId) {
                console.warn('无法获取用户ID，无法获取通知设置');
                return false;
            }

            try {
                const response = await messagesApi.getUserSettings(userId);

                if (response && response.code === 200 && response.data && response.data.notification_settings) {
                    this.settings = response.data.notification_settings;
                    return true;
                } else {
                    console.warn('获取通知设置失败:', response);
                    return false;
                }
            } catch (error) {
                console.error('获取通知设置出错:', error);
                return false;
            }
        }
    }
}) 